package com.ruisoft.base.controller;

import com.ruisoft.base.dao.BaseDao;
import com.ruisoft.common.SysCache;
import com.ruisoft.common.SysConstants;
import com.ruisoft.core.json.JSONMap;
import com.ruisoft.core.json.JSONUtil;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.web.bind.annotation.ModelAttribute;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;


public class BaseController {
    private static final Logger LOG = Logger.getLogger(BaseController.class);

    protected HttpServletRequest request = null;

    protected HttpSession session = null;

    protected HttpServletResponse response = null;

    @ModelAttribute
    protected void setContext(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }

    public static final Pattern PAT_PARAM = Pattern.compile("^(?:[^=&]+=[^=&]*&)*(?:[^=&]+=[^=&]*)$");

    protected final void response(String json)
            throws IOException {
        new JSONUtil().outputJSON(response, json);
    }

    protected final void response(JSONMap<? extends Object, ? extends Object> json)
            throws IOException {
        new JSONUtil().outputJSON(response, json);
    }

    protected JSONObject getReqData() throws Exception {
        String info = request.getReader().readLine();
        LOG.debug("请求参数：" + info);

        if (PAT_PARAM.matcher(info).matches()) {
            String[] param = info.split("&");
            String k = null, v = null;
            JSONObject json = new JSONObject();
            for (String p : param) {
                try {
                    k = p.split("=")[0];
                    v = p.split("=")[1];
                } catch (ArrayIndexOutOfBoundsException e) {
                    v = "";
                } finally {
                    json.put(k, v);
                }
            }
            return json;
        }

        return new JSONObject(info);
    }
    /**
     *
     * @return
     */
    public String getCurrentUser(){
        try {
            return ((JSONObject) session.getAttribute(SysConstants.USER_INFO
                    .toString())).getString("code");
        } catch (JSONException e) {
            e.printStackTrace();
            return "";
        }
    }
    
	private static final String RESPONSE_STR = "{\"Rows\":{rows},\"Total\":\"{total}\"}";

	//private static final JSONArray JSONArray = null;
	
	private JSONObject reqData = null;
	
	@Resource
	protected BaseDao baseDAO = null;

	public void query(String entityName) {
		JSONMap<String, Object> returnJson = new JSONMap<String, Object>(JSONMap.TYPE.OBJECT);
		try {
			if (reqData == null)
				reqData = getReqData();
			
			reqData = reqData.isNull("data") ? reqData.put("data","{}") :reqData;
			
			// 查询实体名称
			//String entityName = reqData.getString("en");
			if (entityName == null || SysCache.get(entityName) == null) {
				returnJson.put("status", "-1");
				returnJson.put("msg", "没有指定查询实体名称");
			} else {
				// l-list 线性结构，默认；t-tree 树型结构			 
				String returnType = reqData.isNull("rt") ? "l" : reqData.getString("rt"); 				
				// 是否分页
				boolean isPager = reqData.getBoolean("p");
				// 当前页码
				int currentPage = reqData.isNull("cp") ? 1 : reqData.getInt("cp");
				// 每页记录数
				int pageSize = reqData.isNull("ps") ? 20 : reqData.getInt("ps");

				List<JSONObject> result = null;
				String rows = null, total = "0";
				if (isPager) {
					result = baseDAO.queryForPage(entityName, reqData.getString("data"), currentPage, pageSize);
					total = result.get(0).getString("total");
					result.remove(0);
				} else {
					result = baseDAO.query(reqData.getString("data"), entityName);
				}

				if ("t".equalsIgnoreCase(returnType)) {
					rows = treeData(result);
				} else {
					rows = new JSONArray(result).toString();
				}

				returnJson.put("status", "1");
				returnJson.put("data", RESPONSE_STR.replaceFirst("\\{total\\}", total).replaceFirst("\\{rows\\}", rows));
				response(RESPONSE_STR.replaceFirst("\\{total\\}", total).replaceFirst("\\{rows\\}", rows));
			}
		} catch (Exception e) {
			LOG.error("执行查询操作发生错误", e);
			returnJson.put("status", "-2");
			returnJson.put("msg", "执行查询操作发生错误");
		} finally {
			try {
				LOG.debug(returnJson);
				response(returnJson);
			} catch (IOException e) {
				LOG.error("查询返回信息时发生错误", e);
				;
			}
			reqData = null;
		}
	}

	protected String treeData(List<JSONObject> data) {
		return new JSONMap<String, String>(JSONMap.TYPE.ARRAY).toString();
	}
}